package controller

import (
	"context"
	"github.com/gin-gonic/gin"
	"goods_bff/goods_proto"
	"goods_bff/pkg"
	"net/http"
	"strconv"
)

func GoodsListByHot(c *gin.Context) {
	comment := pkg.Comment()
	hot, err := comment.GoodsListByHot(context.Background(), &goods_proto.GoodsListByHotRequest{})
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{
			"code": -1,
			"msg":  "查询失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "success",
		"data": hot,
	})
}

// es列表
func GoodsList(c *gin.Context) {
	keywords := c.Query("keywords")
	page := c.Query("page")
	limit := c.Query("limit")
	pageInt, _ := strconv.Atoi(page)
	limitInt, _ := strconv.Atoi(limit)
	comment := pkg.Comment()
	list, err := comment.GoodsList(context.Background(), &goods_proto.GoodsListRequest{
		Keywords: keywords,
		Page:     int64(pageInt),
		Limit:    int64(limitInt),
	})
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{
			"code": -1,
			"msg":  "查询失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "success",
		"data": map[string]interface{}{
			"list":  list.GoodsInfo,
			"total": list.Total,
		},
	})
}

func GoodsDetail(c *gin.Context) {
	id := c.Query("id")
	idInt, _ := strconv.Atoi(id)
	comment := pkg.Comment()
	goods, err := comment.GoodsDetail(context.Background(), &goods_proto.GoodsDetailRequest{Id: int64(idInt)})
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{
			"code": -1,
			"msg":  "查询失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "success",
		"data": goods,
	})
}

func CreateComment(c *gin.Context) {
	comments := c.PostForm("comments")
	goodsId := c.PostForm("goods_id")
	idInt, _ := strconv.Atoi(goodsId)
	comment := pkg.Comment()
	_, err := comment.CreateComment(context.Background(), &goods_proto.CreateCommentRequest{
		GoodsId:  int64(idInt),
		Comments: comments,
	})
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{
			"code": -1,
			"msg":  "添加失败",
			"data": nil,
		})
		return
	}
	pkg.FuncRequest(c)
}

func AddShopping(c *gin.Context) {
	num := c.PostForm("num")
	goodsId := c.PostForm("goods_id")
	idInt, _ := strconv.Atoi(goodsId)
	numInt, _ := strconv.Atoi(num)
	comment := pkg.Comment()
	_, err := comment.AddShopping(context.Background(), &goods_proto.AddShoppingRequest{
		GoodsId: int64(idInt),
		Num:     int64(numInt),
	})
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{
			"code": -1,
			"msg":  "添加失败",
			"data": nil,
		})
		return
	}
	pkg.FuncRequest(c)
}
